import {createRouter, createWebHistory} from "vue-router";
import {defineAsyncComponent} from "vue";

const routes = [
    {
        path: '/',
        name: 'main',
        component: () => import('@/layout/index.vue')
    },
    {
        path: '/login',
        component: () => import('@/views/login.vue'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/error/404.vue')
    }
]

const dynamicRoutes = [
    {
        path: '/',
        name: '/',
        component: () => import('@/views/index.vue'),
        meta: {
            title: '后台首页'
        }
    },
    {
        path:'/profile',
        name:'/profile',
        component: () => import('@/views/system/user/profile/index.vue'),
        meta: {
            title: '个人中心'
        }
    }
    // {
    //     path:'/category/list',
    //     name:'/category/list',
    //     component: () => import('@/views/category/index.vue'),
    //     meta: {
    //         title: '分类列表'
    //     }
    // }
]

export const router = createRouter({
    history: createWebHistory(),
    routes
})

// 先添加固定的动态路由
dynamicRoutes.forEach(route => {
    router.addRoute('main', route)
})

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('../views/**/*.vue')

export function handleRoutes(routes) {
    let isNew = false
    const findMoreRoutes = (arr) => {
        arr.forEach(e => {
            // 如果当前路由有component，就直接添加这个路由
            if (e.component) {
                let item = {...e}
                item.component = modules[`../views/${e.component}.vue`]
                item.meta = {
                    title: e.title,
                    icon: e.icon
                }
                if (!router.hasRoute(item.path)) {
                    router.addRoute('main', item)
                    isNew = true
                }
            }

            // 继续处理children中的路由
            if (e.children && e.children.length > 0) {
                findMoreRoutes(e.children)
            }
        })
    }

    findMoreRoutes(routes)
    return isNew;
}
